package com.mlnx.bluwifi.tp.youRbp;


import com.mlnx.bluwifi.tp.Packet;
import com.mlnx.common.utils.MyLog;

public class YouRBpPacket implements Packet {
    private MyLog log =MyLog.getLog(YouRBpPacket.class);
    private BpLis bpLis;

    public YouRBpPacket(BpLis bpLis) {

        this.bpLis = bpLis;
    }

    @Override
    public void decode(byte[] bytes, int len) {
        if (len >= 4 && bytes[0] == (byte) 0xFD && bytes[1] == (byte) 0xFD &&
                bytes[len - 2] == (byte) 0X0D && bytes[len - 1] == (byte) 0x0A) {
            proceePacket(bytes);
        }
    }

    private void proceePacket(byte[] contant) {

        int state = YouRBpResponse.compareByte(contant);
        if (state == -1) {
            switch (contant[2]) {
                // 实时数据指令
                case (byte) 0xFB:
                    // 	[0xFD,0xFD,0xFB,PressureH, PressureL,0X0D, 0x0A]
                    log.debug("实时数据指令");
                    int pressure = ((0x000000ff & contant[3]) * 256) + 0x000000ff & contant[4];
                    bpLis.pressure(pressure);
                    break;
                // 返回结果指令
                case (byte) 0xFC:
                    //[0xFD,0xFD,0xFC, SYS,DIA,PUL, 0X0D, 0x0A]
                    int sbp = 0x000000ff & contant[3];
                    int dbp = 0x000000ff & contant[4];
                    int heart = 0x000000ff & contant[5];
                    bpLis.bp(System.currentTimeMillis(), sbp, dbp, heart, false);
                    break;
                case (byte) 0xFD:
                    bpLis.error(YouRBpResponse.getErrorMsg(contant[3]));
                    break;
            }
        } else if (state == 0) {
            bpLis.commandOK();
        }
    }


    public static byte[] getStartPacket() {
        return new byte[]{(byte) 0xFD, (byte) 0xFD, (byte) 0xFA, (byte) 0x05, (byte) 0X0D, (byte) 0x0A};
    }

    public static byte[] getStropPacket() {
        return new byte[]{(byte) 0xFD, (byte) 0xFD, (byte) 0xFA, (byte) 0x06, (byte) 0X0D, (byte) 0x0A};
    }


    public interface BpLis {

        void commandOK();

        void commandError(String msg);

        void error(String msg);

        void heartBeat();

        void pressure(int pressure);

        void bp(long time, int sbp, int dbp, int heart, boolean heartEror);
    }
}
